﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Linq;
using System.Web;
using AMS.WorkBill.DataAccess;
using AMS.WorkBill.Entities;
using VitCode.Castle.Helper;

namespace AMS.Web.WorkBill
{
    public class WoCodeCreateHelper
    {
        private static string m_MaxWoCode="";
        private const string HEAD_STRING = "WO";

        public static string GetNewWoCode()
        {
            lock(m_MaxWoCode)
            {
                if(m_MaxWoCode==null || m_MaxWoCode.Length==0)
                {
                    WorkBillAccess acc = new WorkBillAccess();
                    string sql = "Select Max(Code) from AmsWorkBill_WoInfo";
                    try
                    {
                        object val = new SqlHelper().ExecuteScalar(acc.Session, sql);
                        if (val != null)
                            m_MaxWoCode = val.ToString();
                    }
                    finally
                    {
                        acc.CloseSession();
                    }
                }

                if(m_MaxWoCode!=null && m_MaxWoCode.Length == 14)
                {
                    string strHead = m_MaxWoCode.Substring(0, 2);
                    string strDate = m_MaxWoCode.Substring(2, 8);
                    string strNo = m_MaxWoCode.Substring(10, 4);
                    if(strDate == DateTime.Now.ToString("yyyyMMdd"))
                    {
                        int tempInt = Convert.ToInt32("1" + strNo);
                        tempInt++;
                        string strNewCodeNo = tempInt.ToString().Substring(1, 4);
                        m_MaxWoCode = strHead + strDate + strNewCodeNo;
                    }
                    else
                        m_MaxWoCode = HEAD_STRING + DateTime.Now.ToString("yyyyMMdd") + "0001";
                }
                else
                {
                    m_MaxWoCode = HEAD_STRING + DateTime.Now.ToString("yyyyMMdd") + "0001";
                }
            }
            return m_MaxWoCode;
        }
    }
}
